/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.entity.Client;
import ejb.entity.Compte;
import ejb.facade.ClientFacadeRemote;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Trasheur
 */
@WebServlet(name = "AjouterCompte", urlPatterns = {"/AjouterCompte"})
public class AjouterCompte extends HttpServlet {

    @EJB
    private ClientFacadeRemote clientFacade;
    @Resource(mappedName = "jms/NewCompteMessageFactory")
    private ConnectionFactory compteConnectionFactory;
    @Resource(mappedName = "jms/NewCompteMessage")
    private Queue compteQueue;
    @Resource(mappedName = "jms/UpdateClientMessageFactory")
    private ConnectionFactory clientConnectionFactory;
    @Resource(mappedName = "jms/UpdateClientMessage")
    private Queue clientQueue;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        // Add the following code to send the JMS message
        Integer id_client = Integer.valueOf(request.getParameter("id_client"));
        String type_compte = request.getParameter("type_compte");
        Integer solde = null;
        if (request.getParameter("solde") != null) {
            solde = Integer.valueOf(request.getParameter("solde"));
        }
        if ((id_client != null) && (solde != null) && (type_compte != null)) {
            try {
                Connection connection = compteConnectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer messageProducer = session.createProducer(compteQueue);
                ObjectMessage message = session.createObjectMessage();

                Compte e = new Compte();
                e.setTypeCompte(type_compte);
                e.setSolde(solde);
                e.setIdClient(id_client);
                e.setDateDeCreation(new Date());
                e.setDateSolde(new Date());

                message.setObject(e);
                messageProducer.send(message);
                messageProducer.close();
                session.close();
                connection.close();

                //

                Client client = clientFacade.find(id_client);

                connection = clientConnectionFactory.createConnection();
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

                messageProducer = session.createProducer(clientQueue);

                message = session.createObjectMessage();
                client.setNombreCompte(client.getNombreCompte() + 1);
                Logger.getLogger(AjouterCompte.class.getName()).log(Level.SEVERE, null, client.getNombreCompte());

                message.setObject(client);
                messageProducer.send(message);
                messageProducer.close();
                session.close();
                connection.close();

                response.sendRedirect("ListClient");
            } catch (JMSException ex) {
                ex.printStackTrace();
            }
        }

        PrintWriter out = response.getWriter();
        try {
            Client client = clientFacade.find(id_client);
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Ajouter un compte</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Ajouter un compte a " + client.getNom() + " " + client.getPrenom() + "</h1>");
            out.println("<form>");
            out.println("Type de compte : <select name='type_compte'>");
            out.println("<option>Compte Courant</option>");
            out.println("<option>Livret A</option>");
            out.println("<option>Livret Jeune</option>");
            out.println("</select><br/>");
            out.println("Solde : <input type='number' min='0' name='solde' value='0'><br/>");
            out.println("<input type='hidden' name='id_client' value='" + id_client + "'><br/>");
            out.println("<input type='submit'><br/>");
            out.println("</form>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
